package xyz.penghaonan.p2plib.job.operations;

import java.util.concurrent.atomic.AtomicBoolean;

import xyz.penghaonan.p2plib.utils.P2PActionListener;
import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.job.base.BaseOperation;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PHelper;
import xyz.penghaonan.p2plib.helper.sockethelper.ServerSocketHelper;

public class CreateGroupOperation extends BaseOperation {
    public CreateGroupOperation() {
    }

    @Override
    public void doOperation() {
        notifyProgress(0.2f, "创建群组");
        final AtomicBoolean createGroupSuccess = new AtomicBoolean();
        WifiP2PHelper wifiP2PHelper = P2PManager.getP2PHelper();
        wifiP2PHelper.createGroup(new P2PActionListener() {

            @Override
            public void onSuccess() {
                super.onSuccess();
                createGroupSuccess.set(true);
                operationContinue();
            }

            @Override
            public void onFailure(int reason) {
                super.onFailure(reason);
                operationContinue();
            }
        });
        operationWait();
        if (!createGroupSuccess.get()) {
            notifyProgress(1f, "创建群组失败");
            setResult(Result.result(createGroupSuccess.get(), "Create group failed"));
            return;
        }
        notifyProgress(0.8f, "创建群组成功");
        notifyProgress(1f, "创建通信管道");
        ServerSocketHelper serverSocketHelper = P2PManager.getServerSocketHelper();
        setResult(Result.result(createGroupSuccess.get(), "Create group success"));
    }

    @Override
    public String getName() {
        return "创建群组";
    }
}
